Golang : Setting variable value with ldflags
This short tutorial will demonstrate how to initialize a variable value during runtime at the stage of compilation/linking. Go linker has an option to set the value of an uninitialised string variable:
-X symbol value
Set the value of an otherwise uninitialized string variable.
The symbol name should be of the form importpath.name,
as displayed in the symbol table printed by "go tool nm".
For example :
package main
import "fmt"
var str string
func main() {
fmt.Println(str)
}
and execute the program with -ldflags
to initialize the str variable value
$ go run -ldflags "-X main.str abc" main.go
or if you prefer, build it first into executable binary :
$ go build -ldflags "-X main.str 'abc'" main.go && ./main
Output :
abc
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.7k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+26.4k Golang : Encrypt and decrypt data with AES crypto
+9.5k Golang : Qt get screen resolution and display on center example
+14.6k Golang : How to check for empty array string or string?
+27.9k Golang : Connect to database (MySQL/MariaDB) server
+16.8k Golang : Capture stdout of a child process and act according to the result
+10.4k Golang : ISO8601 Duration Parser example
+5.6k Unix/Linux : Get reboot history or check when was the last reboot date
+9.9k Golang : Bcrypting password
+6.5k Golang : When to use make or new?
+9.5k Golang : Eroding and dilating image with OpenCV example